package com.meisiabc.support.wechat.fix;

import com.riversoft.weixin.common.WxClient;
import com.riversoft.weixin.common.util.JsonMapper;
import com.riversoft.weixin.mp.MpWxClientFactory;
import com.riversoft.weixin.mp.base.AppSetting;
import com.riversoft.weixin.mp.base.WxEndpoint;
import com.riversoft.weixin.mp.template.Data;
import com.riversoft.weixin.mp.template.MiniProgram;
import com.riversoft.weixin.mp.template.Templates;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class FixTemplates extends Templates {
    private WxClient wxClient;

    public static FixTemplates with(AppSetting appSetting) {
        FixTemplates templates = new FixTemplates();
        templates.setWxClient(MpWxClientFactory.getInstance().with(appSetting));
        return templates;
    }

    @Override
    public void setWxClient(WxClient wxClient) {
        this.wxClient = wxClient;
    }

    public void sendFix(String toUser, String templateId, String url, MiniProgram miniProgram, Map<String, Data> messages) {
        String sendUrl = WxEndpoint.get("url.template.send");
        MessageWrapper messageWrapper = new MessageWrapper();
        messageWrapper.setToUser(toUser);
        messageWrapper.setTemplateId(templateId);

        if (url != null) {
            messageWrapper.setUrl(url);
        }
        if (miniProgram != null) {
            messageWrapper.setMiniProgram(miniProgram);
        }
        messageWrapper.setData(messages);

        String json = JsonMapper.defaultMapper().toJson(messageWrapper);

        log.debug("template message, send message: {}", json);
        String response = wxClient.post(sendUrl, json);
    }
}
